import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/routers/router_path.dart';
import 'package:flutter_app/routers/router_utils.dart';

class SplashPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SplashState();
}

class _SplashState extends State<SplashPage> {
  final String _splash = 'assets/images/splash.jpg';

  //倒计时按钮状态控制
  StreamController<int> _streamController = StreamController.broadcast();

  //倒计时显示秒数
  int _countDown = 5;

  //数据传递
  Sink<int> _sink;

  //倒计时
  Timer _timer;

  @override
  void initState() {
    super.initState();
    _sink = _streamController.sink;
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_countDown <= 0) {
        _toHome();
        return;
      }
      _countDown--;
      _sink.add(_countDown);
    });
  }

  @override
  void dispose() {
    _streamController.close();
    _timer.cancel();
    super.dispose();
  }

  void _toHome() {
    RouterUtils.push(context, RouterPath.home, replace: true);
  }

  void _toLogin() {
    RouterUtils.push(context, RouterPath.login);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Stack(
            children: [
              Align(
                  alignment: Alignment.topRight,
                  child: Container(
                    margin: const EdgeInsets.all(20),
                    width: 60,
                    height: 30,
                    alignment: Alignment.center,
                    child: StreamBuilder(
                      builder: (context, snapshot) => TextButton(
                        child: Text('$_countDown s',
                            style:
                                TextStyle(color: Colors.black, fontSize: 12)),
                        onPressed: () => {_toHome()},
                      ),
                      stream: _streamController.stream,
                      initialData: _countDown,
                    ),
                    decoration: BoxDecoration(
                        color: Colors.grey,
                        borderRadius: BorderRadius.all(Radius.circular(20))),
                  )),
              Align(
                alignment: Alignment.center,
                child: Image.asset(_splash, width: 240, height: 160),
              )
            ],
          ),
        ));
  }
}
